﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DefaultScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;

namespace Klient.Forms
{
    public partial class MyCustomers : PhoneApplicationPage
    {
        #region Dependency Property
        public static DependencyProperty AllCustomersProperty = DependencyProperty.Register(
            "AllCustomers", typeof(ObservableCollection<Customers>), typeof(MyCustomers), null);
        public ObservableCollection<Customers> AllCustomers
        {
            get
            {
                return (ObservableCollection<Customers>)GetValue(AllCustomersProperty);
            }
            set
            {
                SetValue(AllCustomersProperty, value);
            }
        }
        #endregion

        DefaultScopeOfflineContext context;


        public MyCustomers()
        {
            DataContext = this;

            context = new DefaultScopeOfflineContext("customers", new Uri("http://localhost:49342/DefaultScopeSyncService.svc/"));
   
            context.CacheController.ControllerBehavior.SerializationFormat = Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;
            context.CacheController.RefreshCompleted += new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(CacheController_RefreshCompleted);
            context.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(context_LoadCompleted);
            this.Loaded += new RoutedEventHandler(MyCustomers_Loaded);

            InitializeComponent();
        }

        void MyCustomers_Loaded(object sender, RoutedEventArgs e)
        {
            context.LoadAsync();
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                delegate
                {
                    AllCustomers = new ObservableCollection<Customers>(context.CustomersCollection);
                }
                );
        }

        void CacheController_RefreshCompleted(object sender, Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            if (e.Error != null)
                Dispatcher.BeginInvoke(delegate { MessageBox.Show(e.Error.ToString()); });
        }
    }
}